package com.sky.service.common.Impl;

import com.sky.exception.CourierNotExistException;
import com.sky.mapper.common.ShortUrlMapper;
import com.sky.mapper.redis.CourierTradeOrderMapper;
import com.sky.mapper.redis.RedisCourierMapper;
import com.sky.pojo.Courier;
import com.sky.pojo.CourierTradeOrder;
import com.sky.result.Result;
import com.sky.service.common.CommonService;
import com.sky.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class commonServiceImpl implements CommonService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private CourierTradeOrderMapper courierTradeOrderMapper;
    @Resource
    private RedisCourierMapper redisCourierMapper;
    @Resource
    private ShortUrlMapper shortUrlMapper;
    @Override
    public Result sendMessage(String telephone) {
        //1.短信发送
        String code = "";
        //生成随机6为数字得验证🐎
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            code += random.nextInt(10);
        }
        //短息发送
        // alismsTemplate.sendMessage(telephone,code);
        //2.保存到redis
        String key = "code:" + telephone;
        redisTemplate.opsForValue().set(key, code, 600, TimeUnit.SECONDS);
        return Result.success(code);
    }

    /**
     * rider.html查询位置
     */
    @Override
    public Result loadRouteInfo(Long tradeNo, Long courierId, LocalDateTime expire) {
        //判断订单是否已经完成，如果已经完成，那么都不允许查看
        CourierTradeOrder courierTradeOrder= courierTradeOrderMapper.selectByTradeNo(tradeNo);
        //判断运单是否为空
        if (courierTradeOrder==null){
            throw new CourierNotExistException("运单不存在");
        }
        //客户位置的经纬度信息
        String customerAddress = courierTradeOrder.getCustomerAddress();
        String customerLngLat= MapUtils.addressToLnglat(customerAddress);
        //店铺位置的经纬度信息
        String shopAddress = courierTradeOrder.getShopAddress();
        String shopLngLat= MapUtils.addressToLnglat(shopAddress);
        //骑手位置
        Courier courier= redisCourierMapper.selectById(courierId);
        String riderLngLat=courier.getCurLocation();
        String location=customerLngLat+"_"+shopLngLat+"_"+riderLngLat;
        return Result.success(location);
    }
    /**
     * 解析短链接口
     */
    @Override
    public String findShortUrl(String code) {
        return shortUrlMapper.selectByCode(code);
    }
}
